const { get } = require("http");

module.exports = {
	_before: function () { // 通用预处理器

	},
	/**
	 * 作用：分页获取优惠劵数据
	 * @param {int} skip 每页开始条数
	 * @returns {page} 当前页码
	 */
	
	async getDataList(skip) {
		var db = uniCloud.database();
		var cmd = db.command;
		var result = await db.collection('coupons').where({
			switch:true,
			stock:cmd.gt(0)
			}).skip(skip).limit(10).get();
		var data = result.data;
		return data;
	},
	
	/**
	 * 作用：获取用户默认地址
	 * userId:当前用户id
	 */
	async getDefaultAddress(userId){
		var db = uniCloud.database();
		var result = await db.collection('users_address').where({user_id:userId}).get();
		var address = result.data.pop();
		return address;
	},
	
	/**
	 * 作用：领劵
	 */
	async addCoupons(data){
		var db = uniCloud.database();
		var cmd = db.command;
		var date = new Date().getTime();
		//查询该用户是否已经领过该劵
		var exists = await db.collection('get_coupons').where({
			user_id:data.user_id,
			coupons_id:data.coupons_id,
			expire:cmd.gt(date)
		}).get({getOne:true});
		
		if(exists.affectedDocs==0){
			var result = await db.collection('get_coupons').add(data);
			if(result.id){
			   await db.collection('coupons').where({_id:data.coupons_id}).update({
					stock:cmd.inc(-1)
				});
			}
		}else{
			var result = 99;
		}
		
		return result;
		
	},
	
	/**
	 * 根据id查询对应的领取的优惠劵
	 */
	async getDataById(id){
		var db = uniCloud.database();
		var cmd = db.command;
		var result = await db.collection('get_coupons').where({_id:id}).get({getOne:true});
		var getCoupons = result.data[0];
		var couponsId = getCoupons.coupons_id;
		//查询出对应的优惠劵
		var coupons = await db.collection('coupons').where({_id:couponsId}).get({getOne:true});
		return {
			getCoupons:getCoupons,
			coupons:coupons.data[0]
		}
	}
}
